package org.seedltd.upms.service.impl.sys;

import lombok.AllArgsConstructor;
import org.seedltd.base.exception.BusinessException;
import org.seedltd.core.base.BaseServiceImpl;
import org.seedltd.core.utils.Assert;
import org.seedltd.core.utils.tree.TreeUtil;
import org.seedltd.upms.enums.EnableStatus;
import org.seedltd.upms.mapper.sys.SysDeptMapper;
import org.seedltd.upms.model.sys.common.SelectTreeVO;
import org.seedltd.upms.model.sys.entity.SysDept;
import org.seedltd.upms.model.sys.form.SysDeptForm;
import org.seedltd.upms.model.sys.form.SysDeptSearchForm;
import org.seedltd.upms.model.sys.vo.SysDeptVO;
import org.seedltd.upms.service.sys.SysDeptService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 部门管理业务实现
 *
 * @author laizuan
 * @since 2021/07/19
 */
@Service
@AllArgsConstructor
public class SysDeptServiceImpl extends BaseServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Override
    public SysDeptVO findById(Long id) {
        return q().selectById(id, SysDeptVO.class);
    }

    @Override
    public SysDept findByDeptCode(String deptCode) {
        return q()
                .eq(SysDept::getDeptCode, deptCode)
                .eq(SysDept::getEnabled, EnableStatus.ENABLE.getValue())
            .selectOne();
    }

    @Override
    public Long add(SysDeptForm form) {
        Assert.isFalse(q().eq(SysDept::getDeptCode, form.getDeptCode()).checkExists(),
            String.format("部门代码【%s】已存在，请重新填写。", form.getDeptCode()));
        SysDept pojo = u().save(form, new SysDept());
        return pojo.getDeptId();
    }

    @Override
    public boolean update(SysDeptForm form) {
        return u().updateById(form, form.getDeptId());
    }

    @Override
    public boolean delete(Long id) {
        if (q().eq(SysDept::getParentId, id).checkExists()) {
            throw new BusinessException("部门存在子级部门，请先删除子级部门后重试。");
        }
        return u().deleteById(id);
    }

    @Override
    public List<SysDeptVO> list(SysDeptSearchForm searchForm) {
        List<SysDeptVO> deptVOList = q(searchForm).selectList(SysDeptVO.class);
        return new TreeUtil<SysDeptVO>().build(deptVOList);
    }

    @Override
    public List<SelectTreeVO> listSelectTreeDept() {
        return new TreeUtil<SelectTreeVO>().build(baseMapper.listSelectTreeDept());
    }
}